package com.yinhai.model;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;

import com.yinhai.activity.R;

public class ExpressionUtil {
    /**
     * 对spanableString进行正则判断，如果符合要求，则以表情图片代替
     */
    public static void dealExpression(Context context, SpannableString spannableString, Pattern patten, int start,
        boolean isNormal)
        throws Exception {
        Matcher matcher = patten.matcher(spannableString);
        while (matcher.find()) {
            String key = matcher.group();
            if (matcher.start() < start) {
                continue;
            }
            Field field = R.drawable.class.getDeclaredField(key);
            int resId = Integer.parseInt(field.get(null).toString());
            if (resId != 0) {
                /*Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resId);
                ImageSpan imageSpan = new ImageSpan(bitmap);*/
                Drawable drawable = context.getResources().getDrawable(resId);
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());// 这里设置图片的大小
                ImageSpan imageSpan = new ImageSpan(drawable);
                /*if (isNormal) {
                    imageSpan = new ImageSpan(context, bitmap);
                }*/
                
                int end = matcher.start() + key.length();
                spannableString.setSpan(imageSpan, matcher.start(), end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                if (end < spannableString.length()) {
                    dealExpression(context, spannableString, patten, end, isNormal);
                }
                break;
            }
        }
    }
    
    public static SpannableString getExpressionStringByNormal(Context context, String str, String zhengze) {
        return getExpressionString(context, str, zhengze, true);
    }
    
    public static SpannableString getExpressionString(Context context, String str, String zhengze) {
        
        return getExpressionString(context, str, zhengze, false);
    }
    
    public static SpannableString getExpressionString(Context context, String str, String zhengze, boolean isNormal) {
        SpannableString spannableString = new SpannableString(str);
        Pattern sinaPatten = Pattern.compile(zhengze, Pattern.CASE_INSENSITIVE); // 通过传入的正则表达式来生成一个pattern
        try {
            dealExpression(context, spannableString, sinaPatten, 0, isNormal);
        } catch (Exception e) {
            Log.e("dealExpression", e.getMessage());
        }
        return spannableString;
    }
}